﻿using System;
using System.Web;
using JustTest.Models;

namespace JustTest
{
    public class ImageHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["userId"]))
            {
                var userId = context.Request.QueryString["userId"];
             
                    var result = RetrieveUserImage(userId, context);
                    if (result != null)
                    {
                        context.Response.BinaryWrite(result);
                        context.Response.ContentType = "image/png";
                        context.Response.End();
                    }
             }
            
        }

        private Byte[] RetrieveUserImage(string userId, HttpContext context)
        {
            var ctx = new JustTestDb();
            var user = ctx.Users.Find(userId);

            if (user != null)
            {
                if (user.ProfilePicture != null)
                {
                    return user.ProfilePicture;
                }
            }

            return null;
        }
    }
}